package com.bwda.dsrs.filecenter.service;

import com.bwda.dsrs.filecenter.domain.po.executionhistory.ExecutionHistoryPo;
import com.bwda.dsrs.filecenter.domain.po.executionpolicy.ExecutionPolicyPo;
import com.bwda.dsrs.filecenter.util.DateTimeUtils;
import com.bwda.dsrs.filecenter.util.SpringUtils;
import com.bwda.dsrs.systemservice.domain.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;

/**
 * 稽核任务执行的抽象类，执行公共方法
 *
 * @author ligai
 * @date 2020/07/17
 **/
public abstract class AbstractResAuditTaskService implements Runnable {

    private static Logger logger = LoggerFactory.getLogger(AbstractResAuditTaskService.class);
    /**
     * 稽核任务历史服务接口
     */
    protected ExecutionHistoryService resAuditTaskHistoryService = SpringUtils.getBean(ExecutionHistoryService.class);

    /**
     * 调用数据库扫描接口
     */
    protected DbScanResultService dbScanResultService = SpringUtils.getBean(DbScanResultService.class);


    /**
     * 调用策略详情接口
     */
    protected ExecutionPolicyService executionPolicyService = SpringUtils.getBean(ExecutionPolicyService.class);

    /**
     * 需执行的任务对象
     */
    protected ExecutionPolicyPo taskPo;


    /**
     * 任务执行方式 1:由页面触发的任务立即执行 2:由定时任务触发的定时执行
     */
    protected Long taskExecutionType;

    @Override
    public void run() {
        logger.info("start a new thread to execute task:{}", taskPo);
        executeTask(taskPo);
    }

    /**
     * 执行稽核任务
     *
     * @param taskPo 任务对象
     * @return boolean
     */
    public boolean executeTask(ExecutionPolicyPo taskPo) {
        if (taskPo == null) {
            logger.error("executed taskPo is null.");
            return false;
        }

        logger.info("begin to execute TaskId:{}, TaskName:{}", taskPo.getExecutionPolicyId(), taskPo.getExecutionPolicyName());

        //任务执行开始日志
        ExecutionHistoryPo historyPo = newTaskHistoryRecord(taskPo.getExecutionPolicyId());
        Long historyId = historyPo.getHistoryId().longValue();


        //调用具体任务的子类方法abstractExecuteTask(taskPo, historyId);
        java.util.List<Integer> dbGroupIds = new ArrayList<Integer>();

        ExecutionPolicyPo po = executionPolicyService.queryAuditTaskInfo(taskPo.getExecutionPolicyId());

        if (po.getTaskDbGroupPos().size() < 0) {
            logger.error("po.getTaskDbGroupPos().size() < 0");
            return false;
        }
        for (int i = 0; i < po.getTaskDbGroupPos().size(); i++) {
            dbGroupIds.add(po.getTaskDbGroupPos().get(i).getDbGroupId().intValue());
        }
        logger.info("--------dbGroupIds="+dbGroupIds+"---------getTaskId="+historyPo.getTaskId()+"---------getHistoryId="+historyPo.getHistoryId()+"-------getLineNumber="+taskPo.getLineNumber());

        //敏感扫描开始
        Boolean result=dbScanResultService.scanDbGroup(dbGroupIds,historyPo.getTaskId(),historyPo.getHistoryId(),taskPo.getLineNumber());

        if(!result){
            logger.error("数据扫描出错 result == "+result);
            return false;
        }
        /*
         //资源数量
        int index = 1;
        int resourceSize = 100;
        //计算进度百分比
        Long process = Math.round((double) index++ / (double) resourceSize * 100);
        //当前执行时长
        Long tmpExeDur = DateTimeUtils.minusDate(historyPo.getBeginTime(), DateTimeUtils.getNowDate());
        //更新任务执行进度
        resAuditTaskHistoryService.updateTaskHistoryProcess(historyId, process, tmpExeDur);
        //记录任务结束日志
        historyPo = updateTaskHistoryRecord(historyPo);
        */

        return true;
    }

    /**
     * 任务开始日志记录
     *
     * @param auditTaskId 任务ID
     * @return ExecutionHistoryPo
     */
    private ExecutionHistoryPo newTaskHistoryRecord(Long auditTaskId) {
        ExecutionHistoryPo historyPo = new ExecutionHistoryPo();
        //任务ID
        historyPo.setTaskId(auditTaskId.intValue());
        //任务开始时间
        historyPo.setBeginTime(DateTimeUtils.getNowDate());
        historyPo.setEndTime(DateTimeUtils.getNowDate());
        historyPo.setExecutionStatus(Constants.ResAuditTaskExeStatus.TES_EXECUTING.intValue());
        historyPo.setResult(Constants.ResAuditTaskExeResult.ER_SUCCESS.intValue());
        historyPo = resAuditTaskHistoryService.insertPo(historyPo);

        return historyPo;
    }

    /**
     * 任务结束日志更新
     *
     * @param historyPo 历史记录对象
     * @return ExecutionHistoryPo
     */
    private ExecutionHistoryPo updateTaskHistoryRecord(ExecutionHistoryPo historyPo) {
        //任务完成状态
        historyPo.setExecutionStatus(Constants.ResAuditTaskExeStatus.TES_EXECUTED.intValue());
        historyPo.setSpeedProgress(Constants.ResAuditTaskExeResult.ER_FULL_PROCESS.intValue());
        historyPo.setEndTime(DateTimeUtils.getNowDate());
        historyPo.setResult(Constants.ResAuditTaskExeResult.ER_SUCCESS.intValue());
        //该任务的执行时长
        historyPo.setExeDuration(DateTimeUtils.minusDate(historyPo.getBeginTime(), historyPo.getEndTime()));
        //更新执行日志的结束时间和结束状态
        resAuditTaskHistoryService.update(historyPo);

        return historyPo;
    }


}
